package com.pi.community.controller;

import com.alibaba.dubbo.rpc.RpcException;
import com.homelock.common.vo.PageResp;
import com.homelock.common.vo.Resp;
import com.homelock.domain.query.ComHouseholdQuery;
import com.homelock.domain.query.ComOpenRecordQuery;
import com.homelock.dubbo.service.CommunityManagerService;
import com.pi.base.common.BasePage;
import com.pi.base.common.BaseResult;
import com.pi.base.common.SearchPage;
import com.pi.base.controller.BaseController;
import com.pi.base.util.ValidUtil;
import com.pi.base.vo.SelectVO;
import com.pi.community.common.CommunityConst;
import com.pi.community.common.enumeration.TriggerTypeEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@RequestMapping("/community/household")
@Controller
public class HouseholdController extends BaseController {
    static final Logger logger = LoggerFactory.getLogger(HouseholdController.class);

    /**
     * 引入服务提供者
     */
    @Resource(name = "communityManagerService")
    private CommunityManagerService communityManagerService;

    @RequestMapping("list")
    public String list(ModelMap model) {
        return "community/household/list";
    }



    @RequestMapping("goadd")
    public String goAdd(ModelMap model) {
        return "community/household/householdadd";
    }

    @RequestMapping("query")
    @ResponseBody
    public Object queryHouseholdList(@ModelAttribute SearchPage searchPage, @RequestParam(required=false)String queryName,
                                   @RequestParam(required=false)String queryContact,
                                       @RequestParam(required = false)String queryAddress,
                                       HttpSession httpSession){
        searchPage.setPage((searchPage.getPage() == null) ? 1 : searchPage.getPage());
        searchPage.setRows((searchPage.getRows() == null) ? 0 : searchPage.getRows()); //默认查询全部
        // 查询当前登录管理员对应的物业id
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();

        if(StringUtils.isBlank(reCode) || !reCode.startsWith(CommunityConst.COMMUNITY_PRE)){
            return new BasePage(0);
        }
        Long communityId = 0L;
        try{
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
        }catch (Exception e){
            logger.error("当前管理员的社区编号异常："+reCode);
            return new BasePage(0);
        }
        ComHouseholdQuery query = new ComHouseholdQuery();
        query.setCommunityId(communityId);
        query.setHouseholdContact(queryContact);
        query.setHouseholdName(queryName);
        query.setAddress(queryAddress);
        query.setLimit(searchPage.getRows());
        query.setOffset(searchPage.getStartIndex());
        try {
            PageResp pageResp = communityManagerService.queryPageHousehold(query);
            return new BasePage<>(pageResp.getTotal(), pageResp.getRows());
        }catch (RpcException e){
            e.printStackTrace();
            return BaseResult.newErrorResult("远程服务调用失败");
        }
    }


    @RequestMapping("addhousehold")
    @ResponseBody
    public BaseResult addHousehold(@RequestParam(required=true)String addName,
                                   @RequestParam(required=true)String addContact,
                                   @RequestParam(required=false)String addAddress,
                                               HttpSession httpSession) {
        if(StringUtils.isBlank(addName)){
            return BaseResult.newErrorResult("住户名称不能为空");
        }
        boolean check = ValidUtil.validateMobile(addContact);
        if(!check){
            return BaseResult.newErrorResult("住户联系方式格式错误");
        }

        addAddress = StringUtils.trimToEmpty(addAddress);
        // 查询当前登录管理员对应的物业id
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();
        Long communityId = 0L;
        try {
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
        } catch (Exception e) {
            logger.error("当前管理员的社区编号异常：" + reCode);
            return BaseResult.newErrorResult("当前管理员的社区编号异常");
        }
        try {
            Resp resp = communityManagerService.insertCommunityHousehold(communityId, addName, addContact, addAddress);
            if (resp.equalOk()) {
                return BaseResult.newSuccessResult();
            }
            return BaseResult.newErrorResult(resp.getMsg());
        }catch (RpcException e){
            return BaseResult.newErrorResult("远程服务调用失败");
        }
    }

    @RequestMapping("updatehousehold")
    @ResponseBody
    public BaseResult updateHousehold(@RequestParam(required=true)Long id,
                                      @RequestParam(required=true)String name,
                                      @RequestParam(required=true)String contact,
                                      @RequestParam(required=false)String addAddress,
                                      HttpSession httpSession) {
        boolean check = ValidUtil.validateMobile(contact);
        if(!check){
            return BaseResult.newErrorResult("住户联系方式格式错误");
        }
        if(StringUtils.isBlank(name)){
            return BaseResult.newErrorResult("住户名不能为空");
        }
        addAddress = StringUtils.trimToEmpty(addAddress);
        Resp resp = communityManagerService.updateCommunityHousehold(id,name,contact,addAddress);
        if (resp.equalOk()) {
            return BaseResult.newSuccessResult();
        }
        return BaseResult.newErrorResult(resp.getMsg());
    }

    @RequestMapping("delhousehold")
    @ResponseBody
    public BaseResult delHousehold(@RequestParam(required=true)Long id,HttpSession httpSession) {
        Resp resp = communityManagerService.delCommunityHousehold(id);
        if (resp.equalOk()) {
            return BaseResult.newSuccessResult();
        }
        return BaseResult.newErrorResult(resp.getMsg());
    }

    @RequestMapping("delhouseholds")
    @ResponseBody
    public BaseResult delhouseholds(@RequestParam(required=true)String ids){
        String[] idArray = ids.split(",");
        List<Long> idList = new ArrayList<Long>(idArray.length);
        for(String id:idArray){
            try{
               Long item = Long.valueOf(id);
               idList.add(item);
            }catch (Exception e){}
        }
        if(CollectionUtils.isEmpty(idList)){
            return BaseResult.newSuccessResult();
        }
        Resp resp = communityManagerService.delCommunityHouseholds(idList);
        if (resp.equalOk()) {
            return BaseResult.newSuccessResult();
        }
        return BaseResult.newErrorResult(resp.getMsg());
    }


    @RequestMapping("sendnotice")
    @ResponseBody
    public BaseResult sendBatchCommunityNotice(@RequestParam(required=true)String content,
                                   @RequestParam(required=true)String ids,
                                   HttpSession httpSession) {
        List<String> list = Arrays.asList(ids.split(","));
        List<Long> idList = new ArrayList<>(list.size());
        if(StringUtils.isBlank(ids)){
            return BaseResult.newErrorResult("至少包含一个通知住户");
        }
        try {
            list.forEach(item -> idList.add(Long.valueOf(item)));
        }catch (Exception e){
            return BaseResult.newErrorResult("住户通知ID异常");
        }
        if(StringUtils.isBlank(content)){
            return BaseResult.newErrorResult("物业通知不能为空");
        }
        // 查询当前登录管理员对应的物业id
        String reCode = this.getLoginedUserInfo(httpSession).getItem1();
        Long communityId = 0L;
        try {
            communityId = Long.valueOf(reCode.substring(CommunityConst.COMMUNITY_PRE.length()));
        } catch (Exception e) {
            logger.error("当前管理员的社区编号异常：" + reCode);
            return BaseResult.newErrorResult("当前管理员的社区编号异常");
        }
        try {
            Resp resp = communityManagerService.sendBatchCommunityNoice(communityId,idList,content);
            if (resp.equalOk()) {
                return BaseResult.newSuccessResult("通知发送成功",resp.getData());
            }
            return BaseResult.newErrorResult(resp.getMsg(),resp.getData());
        }catch (RpcException e){
            return BaseResult.newErrorResult("远程服务未启动");
        }
    }


}
